package top.zhangjianyong.test.thread;

import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class BaseRunnable implements Runnable {

    private final static List<Thread> threads = new ArrayList<Thread>();
    private static boolean isEnd = false;

    private final static List<String> list = new ArrayList<String>();

    private  int sum  =0;

    public static List<String> getList() {
        return list;
    }

    public boolean isIsEnd(){
         return this.isEnd;
     }

    public void add(Thread thread) {
        threads.add(thread);
    }

    public void remove(Thread thread) {
        threads.remove(thread);
        if (CollectionUtils.isEmpty(threads))
            this.isEnd = true;
    }

    public int getSum() {
        return sum;
    }

    public void run() {

        for (int i =0;i<50;i++){
            // System.out.println(Thread.currentThread().getName()+"-"+i);
            list.add(Thread.currentThread().getName()+"-"+i);
        }
        for (int i =0;i<100;i++){
            this.sum =this.sum+i;
        }

        remove(Thread.currentThread());
    }

    public static void main(String[] args) {

        BaseRunnable runnable =new BaseRunnable();
        Thread thread1 =new Thread(runnable,"thread-1");
        Thread thread2 =new Thread(runnable,"thread-2");
        Thread thread3 =new Thread(runnable,"thread-3");

        runnable.add(thread1);
        runnable.add(thread2);
        runnable.add(thread3);



        thread1.start();
        thread2.start();
        thread3.start();

       while (!runnable.isIsEnd()){
           try {
               Thread.currentThread().sleep(100l);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           // System.out.println(runnable.isIsEnd());
       }

        System.out.println("------------------------------------------结束----------------------------------------------");
        System.out.println(runnable.getSum());
       /*List<String > list =BaseRunnable.getList();
       for (String s :list){
           System.out.println(s);
       }*/


    }

}
